package com.authserver.controller;

import com.authserver.bean.AuthenticationRequest;
import com.authserver.mapper.UserMapper;
import com.authserver.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/auth")
public class AuthenticationController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public ResponseEntity<String> authenticate(@RequestBody AuthenticationRequest request) {
        Authentication authentication =
                new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword());
        authenticationManager.authenticate(authentication);
        UserDetails user = userMapper.findUserByEmail(request.getEmail());
        if (user != null) {
            String token = jwtUtils.generateToken(user);
            return ResponseEntity.ok(token);
        }
        return ResponseEntity.status(400).body("Some error has occurred");
    }

    @GetMapping("/success")
    public ResponseEntity<?> success(@RequestParam Map<String, String> map) {
        if (map.get("code") == null || "".equals(map.get("code"))) {
            return ResponseEntity.status(400).body(map);
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.err.println(authentication);

        Set<SimpleGrantedAuthority> role = Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
        User user = new User("123@qq.com", "123456", role);
        String token = jwtUtils.generateToken(user);
        return ResponseEntity.ok(token);
    }
}

